package ibms_rcp.company.parts;

import ibms_rcp.dao.CompanyManager;
import ibms_rcp.dao.EstateManager;
import ibms_rcp.dao.LeaseManager;
import ibms_rcp.model.Company;
import ibms_rcp.model.Lease;
import ibms_rcp.model.SeqGenereter;
import ibms_rcp.tableViewer.TableContentProvider;
import ibms_rcp.tableViewer.TableLabelProvider;
import ibms_rcp.util.PerspectiveUtils;
import ibms_rcp.verify.CompanyVerify;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

/**
 * 业主基本信息界面
 * @author diamond-wang
 *
 */
public class InfoPart {
	private DataBindingContext m_bindingContext;
	//基本信息编辑按钮
	private Button basicEditButton;
	// 公司名称
	private Text nameText;
	// 公司编号
	private Text codeText;
	// 联系人
	private Text perText;
	// 电话
	private Text telText;
	// 固定电话
	private Text ftelText;
	// 预存款
	private Text balanceText;
	// 提醒阈值
	private Spinner remindSpinner;
	//标志变量，true时为浏览状态，false为编辑状态
	private boolean read=true;
	
	//添加租赁按钮
	private Button leaseAddButton;
	
//	//编辑租赁按钮
//	private Button leaseEditButton;
	
	//结束租赁按钮
	private Button leaseDelButton;
		
	private TableViewer tableViewer;
	private Table table;
	
	private Company company;
	private List<Lease> leases;
	
	@Inject private MApplication application;
	@Inject private EPartService partService;
	@Inject private EModelService modelService;


	/**
	 * 构造函数 注入父组件
	 * 
	 * @param parent
	 */
	@Inject
	public InfoPart(Composite parent) {
		System.out.println("InfoPart constructor");
		company = new Company();
	}

	/**
	 * 添加控件
	 * 
	 * @param parent
	 */
	@PostConstruct
	public void createControls(final Composite parent) {
		GridLayout layout = new GridLayout(1, false);
		layout.marginWidth = 10;
		layout.marginHeight = 10;
		parent.setLayout(layout);
		
		Composite companyInfoComposite = new Composite(parent, SWT.BORDER);
		companyInfoComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		companyInfoComposite.setLayout(new GridLayout(6, false));
		
		Label basicTitle = new Label(companyInfoComposite, SWT.NONE);
		basicTitle.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.BOLD));
		basicTitle.setText("基本信息");
		
		basicEditButton = new Button(companyInfoComposite, SWT.NONE);
		basicEditButton.setText("编辑");
		basicEditButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				if(read){//浏览状态下
					//按钮为编辑，点击变为编辑状态布局，按钮变为“保存”
					toEdit();
				}
				else{//编辑状态下
					//按钮为保存，点击校验、保存信息，按钮变为“编辑”
					//添加公司信息
					addCompanyInfo(company);
					//company信息验证
					String message = CompanyVerify.addCompanyVerify(company);
					//如果是SUCCESS则添加，不是则显示警告信息
					if(message.equals("SUCCESS")){
						CompanyManager.update(company);//保存company
						toRead();//切换为只读状态
					}
					else{
						MessageDialog.openWarning(parent.getShell(), "警告", message);
					}
				}
			}
		});
		
		new Label(companyInfoComposite, SWT.NONE);
		new Label(companyInfoComposite, SWT.NONE);
		new Label(companyInfoComposite, SWT.NONE);
		new Label(companyInfoComposite, SWT.NONE);
		
		// 公司名称
		Label nameLabel = new Label(companyInfoComposite, SWT.RIGHT);
		nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		nameLabel.setText("公司名称：");
		nameText = new Text(companyInfoComposite, SWT.BORDER);
		nameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				3, 1));

		// 公司编号
		Label idLabel = new Label(companyInfoComposite, SWT.RIGHT);
		idLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false,
				1, 1));
		idLabel.setText("公司编号：");
		codeText = new Text(companyInfoComposite, SWT.BORDER);
		codeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1,
				1));
		codeText.setEditable(false);

		// 联系人
		Label perLabel = new Label(companyInfoComposite, SWT.RIGHT);
		perLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		perLabel.setText("联系人：");
		perText = new Text(companyInfoComposite, SWT.BORDER);
		perText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));

		// 电话
		Label telLabel = new Label(companyInfoComposite, SWT.RIGHT);
		telLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		telLabel.setText("电话：");
		telText = new Text(companyInfoComposite, SWT.BORDER);
		telText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));

		// 固定电话
		Label ftelLabel = new Label(companyInfoComposite, SWT.RIGHT);
		ftelLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		ftelLabel.setText("固定电话：");
		ftelText = new Text(companyInfoComposite, SWT.BORDER);
		ftelText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));

		// 预存款
		Label balanceLabel1 = new Label(companyInfoComposite, SWT.RIGHT);
		balanceLabel1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		balanceLabel1.setText("预存款：");
		// Composite balanceComposite = new Composite(parent, SWT.NONE);
		// balanceComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
		// true, false, 1, 1));
		// balanceComposite.setLayout(new GridLayout(3, true));
		balanceText = new Text(companyInfoComposite, SWT.BORDER);
		balanceText.setText("0");
		balanceText.setEditable(false);
		balanceText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		Label balanceLabel2 = new Label(companyInfoComposite, SWT.LEFT);
		balanceLabel2.setText("元");

		// 提醒阈值
		Composite remindComposite = new Composite(companyInfoComposite, SWT.NONE);
		remindComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		remindComposite.setLayout(new GridLayout(3, false));
		Label remindLabel1 = new Label(remindComposite, SWT.RIGHT);
		remindLabel1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		remindLabel1.setText("余额小于");
		remindSpinner = new Spinner(remindComposite, SWT.BORDER);
		// remindSpinner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
		// false, 1, 1));
		Label remindLabel2 = new Label(remindComposite, SWT.LEFT);
		remindLabel2.setText("天开销时提醒充值");
		
		toRead();
		
		//租赁信息
		Composite leaseComposite = new Composite(parent, SWT.NONE);
		leaseComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		leaseComposite.setLayout(new GridLayout(6, false));
		
		Label leaseTitle = new Label(leaseComposite, SWT.NONE);
		leaseTitle.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.BOLD));
		leaseTitle.setText("租赁信息");
		
		//添加租赁
		leaseAddButton = new Button(leaseComposite, SWT.NONE);
		leaseAddButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false,
				false, 1, 1));
		leaseAddButton.setText("添加");
		leaseAddButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				application.getContext().set("lease", null);//将context中lease参数清空
				//切换到添加房间perspective
				MPerspective element = (MPerspective) modelService.find("ibms_rcp.perspective.company.lease", application);
				// Now switch perspective
				partService.switchPerspective(element);
			}
		});
		
//		//编辑租赁
//		leaseEditButton = new Button(leaseComposite, SWT.NONE);
//		leaseEditButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false,
//						false, 1, 1));
//		leaseEditButton.setText("编辑");
//		leaseEditButton.addMouseListener(new MouseAdapter() {
//			public void mouseUp(MouseEvent e) {
//				
//			}
//		});
		
		//结束租赁
		leaseDelButton = new Button(leaseComposite, SWT.NONE);
		leaseDelButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false,
				false, 1, 1));
		leaseDelButton.setText("退租");
		leaseDelButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				//返回选中行的lease
				IStructuredSelection selection = (IStructuredSelection)tableViewer.getSelection();
				Lease lease = (Lease)selection.getFirstElement();
				//如果选中行不是空白行，得到该Lease对应房间的Moi id
				if(lease!=null){
					long leaseId = lease.getId();
					//删除该房间的租赁信息，与业主的挂靠关系，修改实际退租时间
					LeaseManager.endLease(company.getId(), leaseId);
					leases.remove(lease);
					tableViewer.setInput(leases);
				}
			}
		});
		new Label(leaseComposite, SWT.NONE);
		new Label(leaseComposite, SWT.NONE);
		new Label(leaseComposite, SWT.NONE);
		
		//租赁信息表
		tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);
		table = tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		TableViewerColumn seqViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn seqTableColumn = seqViewerColumn.getColumn();
		seqTableColumn.setResizable(false);
		seqTableColumn.setAlignment(SWT.CENTER);
		seqTableColumn.setWidth(40);
		seqTableColumn.setText("序号");
		
		TableViewerColumn buildingViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn buildingTableColumn = buildingViewerColumn.getColumn();
		buildingTableColumn.setResizable(false);
		buildingTableColumn.setAlignment(SWT.CENTER);
		buildingTableColumn.setWidth(50);
		buildingTableColumn.setText("楼栋");
		
		TableViewerColumn floorViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn floorTableColumn = floorViewerColumn.getColumn();
		floorTableColumn.setResizable(false);
		floorTableColumn.setAlignment(SWT.CENTER);
		floorTableColumn.setWidth(50);
		floorTableColumn.setText("楼层");
		
		TableViewerColumn roomViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn roomTableColumn = roomViewerColumn.getColumn();
		roomTableColumn.setResizable(false);
		roomTableColumn.setAlignment(SWT.CENTER);
		roomTableColumn.setWidth(50);
		roomTableColumn.setText("房间");
		
		TableViewerColumn beginLeaseViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn beginLeaseTableColumn = beginLeaseViewerColumn.getColumn();
		beginLeaseTableColumn.setResizable(false);
		beginLeaseTableColumn.setAlignment(SWT.CENTER);
		beginLeaseTableColumn.setWidth(150);
		beginLeaseTableColumn.setText("起租时间");
		
		TableViewerColumn endLeaseViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn endLeaseTableColumn = endLeaseViewerColumn.getColumn();
		endLeaseTableColumn.setResizable(false);
		endLeaseTableColumn.setAlignment(SWT.CENTER);
		endLeaseTableColumn.setWidth(150);
		endLeaseTableColumn.setText("到租时间");
		
		TableViewerColumn beginChargeViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn beginChargeTableColumn = beginChargeViewerColumn.getColumn();
		beginChargeTableColumn.setResizable(false);
		beginChargeTableColumn.setAlignment(SWT.CENTER);
		beginChargeTableColumn.setWidth(150);
		beginChargeTableColumn.setText("开始收费时间");
		
		TableViewerColumn preChargeViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn preChargeTableColumn = preChargeViewerColumn.getColumn();
		preChargeTableColumn.setResizable(false);
		preChargeTableColumn.setAlignment(SWT.CENTER);
		preChargeTableColumn.setWidth(50);
		preChargeTableColumn.setText("预收费");
		
		TableViewerColumn propertyViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn propertyTableColumn = propertyViewerColumn.getColumn();
		propertyTableColumn.setResizable(false);
		propertyTableColumn.setAlignment(SWT.CENTER);
		propertyTableColumn.setWidth(50);
		propertyTableColumn.setText("物业费");
		
		TableViewerColumn elecViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn elecTableColumn = elecViewerColumn.getColumn();
		elecTableColumn.setResizable(false);
		elecTableColumn.setAlignment(SWT.CENTER);
		elecTableColumn.setWidth(50);
		elecTableColumn.setText("电费");
		
		TableViewerColumn userViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn userTableColumn = userViewerColumn.getColumn();
		userTableColumn.setResizable(false);
		userTableColumn.setAlignment(SWT.CENTER);
		userTableColumn.setWidth(100);
		userTableColumn.setText("办理人");
		
		tableViewer.setContentProvider(new TableContentProvider());
		tableViewer.setLabelProvider(new TableLabelProvider());
		
		final String[] columnNames = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
		tableViewer.setColumnProperties(columnNames);
		//编辑器 定义CellEditor数组并指定给前面的TableViewer
		final CellEditor[] editors = new CellEditor[tableViewer.getTable().getColumnCount()];
		//editors[0]-editors[6],editors[10]保留为空，因为不需要显示为Checkbox
		editors[7] = new CheckboxCellEditor(tableViewer.getTable());
		editors[8] = new CheckboxCellEditor(tableViewer.getTable());
		editors[9] = new CheckboxCellEditor(tableViewer.getTable());
		tableViewer.setCellEditors(editors);
		//定义TableViewer的CellModifier，作用是告诉表格如何改变对象的属性值
		//注意在modify()方法里参数element可能是org.eclipse.swt.widgets.Item类型，如果是这种情况要通过Item#getData()得到实际的对象
		tableViewer.setCellModifier(new ICellModifier() {
		    public boolean canModify(Object element, String property) {
		        return property.equals(columnNames[7]) || property.equals(columnNames[8]) || property.equals(columnNames[9]);
		    }
		    public Object getValue(Object element, String property) {
		        Lease item = (Lease) element;
		        if (property.equals(columnNames[7])) {
		            return Boolean.valueOf(item.isPreCharge());
		        }
		        if (property.equals(columnNames[8])) {
		            return Boolean.valueOf(item.isPropCharge());
		        }
		        if (property.equals(columnNames[9])) {
		            return Boolean.valueOf(item.isElecCharge());
		        }
		        return null;
		    }
		    public void modify(Object element, String property, Object value) {
		        if (element instanceof Item){
		            element = ((Item) element).getData();
		            Lease item = (Lease) element;
		            if (property.equals(columnNames[7])) {
		            	item.setPreCharge(((Boolean) value).booleanValue());
		            }
		            else if (property.equals(columnNames[8])) {
		            	item.setPropCharge(((Boolean) value).booleanValue());
		            }
		            else if (property.equals(columnNames[9])) {
		            	item.setElecCharge(((Boolean) value).booleanValue());
		            }
		            tableViewer.setInput(leases);
		        }
		    }
		});

		//双击某条记录时，进入该条租赁记录的编辑视图
		tableViewer.addDoubleClickListener(new IDoubleClickListener(){
			public void doubleClick(DoubleClickEvent event) {
				//返回选中行的lease
				IStructuredSelection selection = (IStructuredSelection)tableViewer.getSelection();
				Lease lease = (Lease)selection.getFirstElement();
				//如果选中行不是空白行，将lease参数传到context中，跳到edit lease视图
				if(lease!=null){
					application.getContext().set("lease", lease);//传递company参数
					//切换到company info perspective
					PerspectiveUtils.switchToPerspective(application, modelService, partService, "ibms_rcp.perspective.company.lease");
				}
			}
			
		});
		
		System.out.println("InfoPart createControls called.");
//		m_bindingContext = initDataBindings();
	}
	
	/**
	 * 显示业主信息视图时，根据context中的company进行显示
	 */
	@Focus
	public void updateDisplay(){
		System.out.println("InfoPart updateCompany called.");
		company = (Company)application.getContext().get("company");
		if(company!=null){//更新基本信息显示
			nameText.setText(company.getName());
			codeText.setText(company.getCode());
			perText.setText(company.getPer());
			telText.setText(company.getTel());
			ftelText.setText(company.getPhone());
			balanceText.setText(String.valueOf(company.getBalance()));
			remindSpinner.setSelection(company.getRemindDay());
			//显示当前业主的租赁信息
			SeqGenereter.clearseq();
			leases = EstateManager.getLeasesByCompany(company.getId());
			tableViewer.setInput(leases);
		}
	}
	/**
	 * 变为浏览状态
	 */
	public void toRead(){
		nameText.setEditable(false);
		perText.setEditable(false);
		telText.setEditable(false);
		ftelText.setEditable(false);
		remindSpinner.setEnabled(false);
		read=true;
		basicEditButton.setText("编辑");
	}
	
	/**
	 * 变为编辑状态
	 */
	public void toEdit(){
		nameText.setEditable(true);
		perText.setEditable(true);
		telText.setEditable(true);
		ftelText.setEditable(true);
		remindSpinner.setEnabled(true);
		read=false;
		basicEditButton.setText("保存");
	}

	@PreDestroy
	public void dispose() {
		System.out.println("BasicInfoPart dispose called.");
	}
//	protected DataBindingContext initDataBindings() {
//		DataBindingContext bindingContext = new DataBindingContext();
//		//
//		IObservableValue observeTextNameTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(nameText);
//		IObservableValue bytesCompanygetNameObserveValue = PojoProperties.value("name").observe(company);
//		bindingContext.bindValue(observeTextNameTextObserveWidget, bytesCompanygetNameObserveValue, null, null);
//		//
//		IObservableValue observeTextCodeTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(codeText);
//		IObservableValue bytesCompanygetCodeObserveValue = PojoProperties.value("code").observe(company);
//		bindingContext.bindValue(observeTextCodeTextObserveWidget, bytesCompanygetCodeObserveValue, null, null);
//		//
//		IObservableValue observeTextPerTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(perText);
//		IObservableValue bytesCompanygetPerObserveValue = PojoProperties.value("per").observe(company);
//		bindingContext.bindValue(observeTextPerTextObserveWidget, bytesCompanygetPerObserveValue, null, null);
//		//
//		IObservableValue observeTextTelTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(telText);
//		IObservableValue bytesCompanygetTelObserveValue = PojoProperties.value("tel").observe(company);
//		bindingContext.bindValue(observeTextTelTextObserveWidget, bytesCompanygetTelObserveValue, null, null);
//		//
//		IObservableValue observeTextFtelTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(ftelText);
//		IObservableValue bytesCompanygetPhoneObserveValue = PojoProperties.value("phone").observe(company);
//		bindingContext.bindValue(observeTextFtelTextObserveWidget, bytesCompanygetPhoneObserveValue, null, null);
//		//
//		IObservableValue observeTextBalanceTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(balanceText);
//		IObservableValue balanceCompanyObserveValue = PojoProperties.value("balance").observe(company);
//		bindingContext.bindValue(observeTextBalanceTextObserveWidget, balanceCompanyObserveValue, null, null);
//		//
//		IObservableValue observeSelectionRemindSpinnerObserveWidget = WidgetProperties.selection().observe(remindSpinner);
//		IObservableValue remindDayCompanyObserveValue = PojoProperties.value("remindDay").observe(company);
//		bindingContext.bindValue(observeSelectionRemindSpinnerObserveWidget, remindDayCompanyObserveValue, null, null);
//		//
//		return bindingContext;
//	}
	
	/**
	 * 添加公司信息
	 */
	public void addCompanyInfo(Company company){
		company.setName(nameText.getText().trim());
		company.setCode(codeText.getText().trim());
		company.setPer(perText.getText().trim());
		company.setTel(telText.getText().trim());
		company.setPhone(ftelText.getText().trim());
		company.setBalance(Double.parseDouble(balanceText.getText().trim()));
		company.setRemindDay(Integer.parseInt(remindSpinner.getText()));
	}
}
